const readline = require('readline');
const axios = require('axios');
const fs = require('fs');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

console.log('\x1b[32m%s\x1b[0m', '--可输入命令或输入help查看帮助--');
console.log('\x1b[32m%s\x1b[0m', '--输入多个命令时，请用空格隔开--');

// 提示输入命令
const promptArgs = () => {
  rl.question('--', (args) => {
    const argsArr = args.split(' ');
    if (args === 'help') {
      displayHelp();
    } else if (argsArr) {
      loginToServer(argsArr);
    }
  });
}

// 显示帮助信息
const displayHelp = () => {
  console.log(`
  --host=<host>--
  --port=<port>--
  --user=<user>--
  --pwd=<pwd>--
  --help--
  `);
}

const instance = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加响应拦截器来保存 cookie
instance.interceptors.response.use(response => {
  const cookies = response.headers['set-cookie'];
  if (cookies) {
    instance.defaults.headers.common['Cookie'] = cookies[0];
  }
  return response;
});

//host=127.0.0.1 port=8080 user=ls pwd=ddd
// 登录服务器
const loginToServer = (argsArr) => {
  instance.post('/routers/user/login',
    {
      username: argsArr[2].split('=')[1],
      password: argsArr[3].split('=')[1]
    }
  ).then((res) => {
    if (res.data.message === '登录成功') {
      console.log('\x1b[32m%s\x1b[0m', '登录成功');
      handleLoginArgs();
    } else {
      console.log('\x1b[31m%s\x1b[0m', '登录失败,请重新登录');
      promptArgs();
    }
  });
}

// 处理登录后的命令
const handleLoginArgs = () => {
  rl.question('--<logining>--', (args) => {
    const argsArr = args.split(' ');
    if (argsArr[0] === 'upload') {
      // 上传文件
      uploadFile(argsArr[1]);
    } else if (argsArr[0] === 'download') {
      // 下载文件
      downloadFile(argsArr[1]);
    } else if (argsArr[0] === 'list') {
      // 显示文件列表
      showFileList();
    } else if (argsArr[0] === 'delete' && argsArr[1].split('.').length > 1) {
      // 删除文件
      deleteFile(argsArr[1]);
    } else if (argsArr[0] === 'rename' && argsArr[1].split('.').length > 1) {
      // 修改文件名
      renameFile(argsArr[1], argsArr[2]);
    } else if (argsArr[0] === 'lpwd') {
      // 显示本地目录路径
      showLocalDir();
    } else if (argsArr[0] === 'lcd') {
      // 修改本地目录路径
      changeLocalDir(argsArr[1]);
    } else if (argsArr[0] === 'mkdir') {
      // 创建服务器文件夹
      createFolder(argsArr[1]);
    } else if (argsArr[0] === 'delete' && argsArr[1].split('.').length <= 1) {
      // 删除服务器文件夹
      deleteFolder(argsArr[1]);
    } else if (argsArr[0] === 'rename' && argsArr[1].split('.').length <= 1) {
      // 修改服务器文件夹名
      renameFolder(argsArr[1], argsArr[2]);
    } else if (argsArr[0] === 'rpwd') {
      // 打印服务器当前目录
      showServerDir();
    } else if (argsArr[0] === 'rcd') {
      // 修改服务器目录
      changeServerDir(argsArr[1]);
    }
    handleLoginArgs();
  });
}

//本地文件绝对路径
let localFilePath = 'E:/UE5FileUpload';

// 上传服务器文件
const uploadFile = (fileName) => {
  instance.post('/routers/file/upload',
    {
      file: localFilePath + '/' + fileName
    }
  ).then((res) => {
    console.log(res.data);
  });
}

// 下载服务器文件
const downloadFile = (fileName) => {
  console.log('正在下载文件:', fileName);
  instance.get('/routers/file/download', {
    params: {
      filename: fileName
    },
    responseType: 'arraybuffer'
  }).then((res) => {
    try {
      fs.writeFileSync(localFilePath + '/' + fileName, Buffer.from(res.data));
      console.log('\x1b[32m%s\x1b[0m', '文件下载成功：' + fileName);
    } catch (err) {
      console.log('\x1b[31m%s\x1b[0m', '文件写入失败：' + err.message);
    }
  }).catch(err => {
    console.log('\x1b[31m%s\x1b[0m', '下载失败：' + err.message);
  });
}

// 显示服务器文件列表
const showFileList = () => {
  instance.get('/routers/file/list').then((res) => {
    //查看服务器当前目录下的文件或目录，目录名后面加 `/`
    console.log('\x1b[32m%s\x1b[0m', '服务器当前目录下的文件或目录：');
    if (res.data.files.length === 0) {
      console.log('\x1b[32m%s\x1b[0m', '当前目录下没有文件或目录');
    } else {
      res.data.files.forEach(file => {
        let count = file.split('.').length;
        if (count < 2) {
          console.log('\x1b[32m%s\x1b[0m', file + '/');
        } else {
          console.log('\x1b[32m%s\x1b[0m', file);
        }
      });
    }
  });
}

// 删除服务器文件
const deleteFile = (fileName) => {
  instance.delete('/routers/file/delete',
    {
      params: {
        filename: fileName
      }
    }
  ).then((res) => {
    console.log(res.data);
  });
}

// 修改服务器文件名
const renameFile = (fileName, newFileName) => {
  instance.put('/routers/file/rename', 
    {
      newFilename: newFileName
    },
    {
      params: {
        filename: fileName
      }
    }
  ).then((res) => {
    console.log(res.data);
  });
}

// 显示本地目录路径
const showLocalDir = () => {
  console.log('\x1b[32m%s\x1b[0m', '本地目录路径：');
  console.log('\x1b[32m%s\x1b[0m', localFilePath);
}

// 修改本地目录路径
const changeLocalDir = (dir) => {
  localFilePath = dir;
  console.log('\x1b[32m%s\x1b[0m', '本地目录路径已修改为：');
  console.log('\x1b[32m%s\x1b[0m', localFilePath);
}

// 创建服务器文件夹
const createFolder = (folderName) => {
  instance.post('/routers/file/createFolder', {
    folderName: folderName
  }).then((res) => {
    console.log(res.data);
  });
}

// 删除服务器文件夹
const deleteFolder = (folderName) => {
  instance.delete('/routers/file/deleteFolder', {
    params: {
      folderName: folderName
    }
  }).then((res) => {
    console.log(res.data);
  });
}

// 修改服务器文件夹名
const renameFolder = (folderName, newFolderName) => {
  instance.put('/routers/file/renameFolder', {
    newFolderName: newFolderName
  }, {
    params: {
      folderName: folderName
    }
  }).then((res) => {
    console.log(res.data);
  });
}

// 打印服务器当前目录
const showServerDir = () => {
  instance.get('/routers/file/showServerDir').then((res) => {
    console.log(res.data);
  });
}

// 修改服务器目录
const changeServerDir = (dir) => {
  instance.get('/routers/file/changeServerDir', {
    params: {
      dir: dir
    }
  }).then((res) => {
    console.log(res.data);
  });
}

promptArgs();
